const express = require('express')
let logs = require('./log/log')
let db = require('./database/init')
var bodyParser = require('body-parser');
const { response } = require('express');
const app = express()
const moment = require('moment');
app.use(bodyParser.json())
app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  // //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  // //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 可以带cookies
  res.header("Access-Control-Allow-Credentials", true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
})
// 查询所有用户
app.get('/getUser', (request, response) => {
  let sql = 'select id,u_account,u_nickname from user_info where u_status=1';
  let params = [];
  db.query(sql, params, function (res, fields) {
    response.status('200').json(res)
  })
})
// 注册用户
app.post('/register', (req, response) => {
  let sql = 'INSERT INTO user_info (u_account,u_password,u_nickname,u_status) VALUES (?,?,?,1)';
  let params = [];
  if (!req.body.u_nickname) {
    req.body.u_nickname = req.body.u_account
  }
  for (var a in req.body) {
    params.push(req.body[a])
  }
  db.query(sql, params, function (res, fields) {
    if (res) {
      response.status('200').json({ code: 200, msg: '注册成功' })
    } else {
      response.status('200').json({ code: 201, msg: '注册失败' })
    }
  })
})
// 用户登录
app.post('/login', (req, response) => {
  let sql = 'select * from user_info where u_account=' + req.body.account;
  let params = [];
  db.query(sql, params, function (res, fields) {
    if (res[0].u_password == req.body.password) {
      if (res[0].u_status == 1) {
        response.status('200').json({ code: 200, msg: '登陆成功', id: res[0].id })
      } else {
        response.status('200').json({ code: 201, msg: '账户已注销' })
      }
    } else {
      response.status('200').json({ code: 201, msg: '密码错误' })
    }
  })
})
// 账号查重
app.get('/searchAccount', (req, response) => {
  let sql = 'select * from user_info where u_account=' + req.query.account;
  let params = [];
  db.query(sql, params, function (res, fields) {
    if (!res.length) {
      response.status('200').json({ code: 200, msg: '账号不存在' })
    } else {
      response.status('200').json({ code: 201, msg: '账号存在' })
    }
  })
})
// 获取用户信息
app.get('/getUserDetil', (req, response) => {
  let sql = 'select u_nickname,u_headPortrait from user_info where id=' + req.query.id;
  let params = [];
  db.query(sql, params, function (res, fields) {
    response.status('200').json({ code: 200, msg: '用户信息', data: res[0] })
  })
})
//注销账号
app.post('/cancelAccount', (req, response) => {
  let sql = 'UPDATE user_info SET u_status=0 where id=' + req.body.id;
  let params = []
  db.query(sql, params, function (res, fields) {
    response.status('200').json({ code: 200, msg: '注销成功' })
  })
})
//恢复账号
app.post('/recoveryAccount', (req, response) => {
  let sql = 'UPDATE user_info SET u_status=1 where u_account=' + req.body.account;
  let params = []
  db.query(sql, params, function (res, fields) {
    response.status('200').json({ code: 200, msg: '恢复成功' })
  })
})
// 发布帖子
app.post('/addPost', (req, response) => {
  let sql = 'INSERT INTO posts (title,content,athor,status,view_num,favor_num,shear_num,comment_num) VALUES (?,?,?,1,0,0,0,0)';
  let params = [];
  for (var a in req.body) {
    params.push(req.body[a])
  }
  db.query(sql, params, function (res, fields) {
    if (res) {
      response.status('200').json({ code: 200, msg: '发布成功' })
    } else {
      response.status('200').json({ code: 201, msg: '发布失败' })
    }
  })
})
// 获取所有帖子
app.get('/getPosts', (req, response) => {
  let sql = 'select * from posts';
  let params = [];
  db.query(sql, params, function (res, fields) {
    response.status('200').json({ code: '200', data: res })
  })
})
// 获取帖子详情
app.get('/getPostDetail', (req, response) => {
  let sql = 'select * from posts where id=' + req.query.id;
  let params = [];
  db.query(sql, params, function (res, fields) {
    if (!req.query.userId) {
      response.status('200').json({ code: '200', data: res })
    } else {
      let sql = `select * from favors where post_id=${req.query.id} and user_id=${req.query.userId}`
      db.query(sql, [], function (res1, fields) {
        if (!res1.length) {
          res[0].isFavor = false;
          response.status('200').json({ code: '200', data: res })
        } else {
          if (res1[0].favor_status) {
            res[0].isFavor = true;
            response.status('200').json({ code: '200', data: res })
          } else {
            res[0].isFavor = false;
            response.status('200').json({ code: '200', data: res })
          }
        }
      })
    }
  })
})
//增加帖子浏览量 \ 添加浏览记录
app.post('/addPostView', (req, response) => {
  var current_time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
  let sql = 'INSERT into view_history (view_athor,post_id,view_date) VALUES (?,?,?)'
  let params = []
  if (req.body.view_athor != 'null') {
    params.push(req.body.view_athor)
  } else {
    params.push(-1)
  }
  params.push(req.body.post_id)
  params.push(current_time)
  db.query(sql, params, function (res, fields) {
    let sqll = 'select view_num from posts where id=' + req.body.post_id
    let paramss = []
    db.query(sqll, paramss, function (res, fields) {
      let view_num = res[0].view_num * 1 + 1
      let sqll = 'UPDATE posts SET view_num=' + view_num + ' where id=' + req.body.post_id;
      let paramss = []
      db.query(sqll, paramss, function (res, fields) {
        response.status('200').json({ code: 200, msg: '成功++' })
      })
    })
  })
})
// 点赞
app.post('/addFavor', (req, response) => {
  let sql = 'select * from favors where post_id=' + req.body.postId * 1 + ' and' + ' user_id=' + req.body.userId * 1 + ';'
  db.query(sql, [], function (res0, fields) {
    if (res0.length) {
      let sql = 'UPDATE favors SET favor_status=1 where id=' + res0[0].id;
      db.query(sql, [], function (res, fields) {
        let sql1 = 'select favor_num from posts where id=' + req.body.postId * 1;
        db.query(sql1, [], function (res, fields) {
          let favor_num = res[0].favor_num * 1 + 1;
          let sql2 = 'UPDATE posts SET favor_num=' + `${favor_num}` + ' where id=' + req.body.postId * 1;
          db.query(sql2, [], function (res, fields) {
            response.status('200').json({ code: 200, msg: '点赞成功' })
          })
        })
      })
    } else {
      var current_time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
      let sql = 'INSERT into favors (favor_date,post_id,user_id,favor_status) VALUES (?,?,?,1)'
      let params = [current_time]
      params.push(req.body.postId * 1)
      params.push(req.body.userId * 1)
      db.query(sql, params, function (res, fields) {
        let sql1 = 'select favor_num from posts where id=' + req.body.postId * 1;
        db.query(sql1, [], function (res, fields) {
          let favor_num = res[0].favor_num * 1 + 1;
          let sql2 = 'UPDATE posts SET favor_num=' + `${favor_num}` + ' where id=' + req.body.postId * 1;
          db.query(sql2, [], function (res, fields) {
            response.status('200').json({ code: 200, msg: '点赞成功' })
          })
        })
      })
    }
  })
})
// 取消点赞
app.post('/cancelFavor', (req, response) => {
  let postId = req.body.postId;
  let sql = 'select * from favors where post_id=' + postId * 1 + ' and' + ' user_id=' + req.body.userId * 1 + ';'
  db.query(sql, [], function (res, fields) {
    if (res) {
      db.query(`UPDATE favors set favor_status=0 where id=${res[0].id}`, [], function (res, fields) {
        db.query(`select * from posts where id=${postId}`, [], function (res, fields) {
          let favor_num = res[0].favor_num;
          db.query(`UPDATE posts set favor_num=${favor_num - 1} where id=${postId}`, [], function (res, fields) {
            response.status('200').json({ code: '200', msg: '取消点赞成功！' })
          })
        })
      })
    }
  })
})
app.listen(8888, () => {
  console.log('服务启动>> 端口号为：8888')
})
